﻿#region Copyright information
// 
// Copyright © 2005-2013 Yongkee Cho. All rights reserved.
// 
// This code is a part of the Biological Object Library and governed under the terms of the
// GNU Lesser General  Public License (LGPL) version 2.1 which accompanies this distribution.
// For more information on the LGPL, please visit http://bol.codeplex.com/license.
// 
// - Filename: Inference.cs
// - Author: Yongkee Cho
// - Email: yongkeecho@gmail.com
// - Date Created: 2012-09-06 11:39 AM
// - Last Modified: 2013-01-25 3:59 PM
// 
#endregion
using System;
using System.Linq;

namespace BOL.Maths.Functions
{
    public static class Inference
    {
        public static double[][] Posterior(double[][] conditionalProbability, double[] prior)
        {
            if (Math.Abs(prior.Sum() - 1) > 1e-5)
                throw new ArgumentException("The sum of prior should be equal to one.");

            int i, j;
            var m = conditionalProbability.Length;
            var n = prior.Length;

            var posterior = new double[m][];
            var marginalProbability = new double[m];

            for (i = 0; i < m; i++)
            {
				if (posterior[i].Length != n)
					throw new ArgumentException("The length of the conditionalProbability[i] should be equal to that of prior.");

                marginalProbability[i] = 0;
                for(j = 0; j < n; j++)
                {
                    posterior[i][j] = conditionalProbability[i][j] * prior[j];
                    marginalProbability[i] += posterior[i][j];
                }
            }

            for (i = 0; i < m; i++)
                for (j = 0; j < n; j++)
                    posterior[i][j] /= marginalProbability[i];

            return posterior;
        }
    }
}
